﻿/*
Copyright (c) 2013, SonicLing
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, 
are permitted provided that the following conditions are met:

    Redistributions of source code must retain the above copyright notice, this 
list of conditions and the following disclaimer.
    Redistributions in binary form must reproduce the above copyright notice, 
this list of conditions and the following disclaimer in the documentation and/or 
other materials provided with the distribution.
    Neither the name of the SonicLing nor the names of its contributors may be 
used to endorse or promote products derived from this software without specific 
prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT 
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR 
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using XmlConfiguration;

namespace Bibtex2Word
{
	public class WordBibXml<T> : XmlConfig<T>
	{
		public WordBibXml()
		{
			Prefix = "b";
		}

		protected override void ReadField(XmlReader reader, FieldInfo field)
		{
			object obj = ReadTypeValue(reader, field.FieldType);
			if (obj != null)
			{
				field.SetValue(this, obj);
			}
		}

		protected override void WriteField(XmlWriter writer, FieldInfo field)
		{
			object value = field.GetValue(this);
			if (value != null || (typeof(string).IsInstanceOfType(value) && string.IsNullOrEmpty(value.ToString())))
			{
				WriteTypedValue(writer, __prefix + field.Name, value, field.FieldType);
			}
		}

		private object ReadTypeValue(XmlReader reader, Type type)
		{
			if (type.IsGenericType && type.GetGenericArguments().Length == 1 &&
				type.GetInterface("System.Collections.IList") != null)
			{
				object fieldObject = Assembly.GetAssembly(type).CreateInstance(type.FullName);
				System.Collections.IList list = fieldObject as System.Collections.IList;
				Type argument = type.GetGenericArguments()[0];
				while (reader.MoveToContent() == XmlNodeType.Element)
				{
					list.Add(ReadTypeValue(reader, argument));
				}
				return fieldObject;
			}
			else if (type.GetInterface("IXmlSerializable") != null)
			{
				object fieldObject = Assembly.GetCallingAssembly().CreateInstance(type.FullName);
				IXmlSerializable val = fieldObject as IXmlSerializable;
				val.ReadXml(reader);
				return fieldObject;
			}
			else
			{
				reader.ReadStartElement();
				if (reader.NodeType != XmlNodeType.Text)
				{
					return null;
				}
				string val = reader.ReadString();
				if (reader.NodeType != XmlNodeType.EndElement)
				{
					return null;
				}
				reader.ReadEndElement();
				if (type.IsEnum)
				{
					return Enum.Parse(type, val);
				}
				else if (type.Equals(typeof(string)))
				{
					return val;
				}
				else if (type.Equals(typeof(int)))
				{
					return int.Parse(val);
				}
				else if (type.Equals(typeof(Guid)))
				{
					return Guid.Parse(val);
				}
				else
				{
					throw new XmlException(string.Format("type {0} is not supported", type.Name));
				}
			}
		}

		private void WriteTypedValue(XmlWriter writer, string name, object value, Type type)
		{
			if (type.IsGenericType && type.GetGenericArguments().Length == 1 &&
				type.GetInterface("IList") != null)
			{
				System.Collections.IList list = value as System.Collections.IList;
				foreach (object obj in list)
				{
					WriteTypedValue(writer, name, obj, obj.GetType());
				}
			}
			else if (type.GetInterface("IXmlSerializable") != null)
			{
				writer.WriteStartElement(name);
				IXmlSerializable val = value as IXmlSerializable;
				val.WriteXml(writer);
				writer.WriteEndElement();
			}
			else if (type.Equals(typeof(Guid)))
			{
				writer.WriteStartElement(name);
				writer.WriteString(((Guid)value).ToString("B"));
				writer.WriteEndElement();
			}
			else
			{
				writer.WriteStartElement(name);
				writer.WriteString(value.ToString());
				writer.WriteEndElement();
			}
		}
	}
}
